package com.kitty.game.role;

import com.kitty.common.utils.SpringUtils;
import com.kitty.common.core.SchedulerManager;
import com.kitty.cross.CrossServerConfig;
import com.kitty.game.ServerService;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.service.shidao.ShiDaoHandler;
import com.kitty.game.activity.service.task.ShuaDaoTaskHandler;
import com.kitty.game.activity.service.task.TowerTaskHandler;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.base.service.BagService;
import com.kitty.game.baxian.message.RespBaxianMengJingInfo;
import com.kitty.game.chat.service.ChatService;
import com.kitty.game.config.GuardSet;
import com.kitty.game.config.Server;
import com.kitty.game.confirm.model.*;
import com.kitty.game.enter.*;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.fight.bean.Fight;
import com.kitty.game.fight.service.FightExecutorService;
import com.kitty.game.fight.service.FightService;
import com.kitty.game.friend.model.Friend;
import com.kitty.game.gate.LoginAuth;
import com.kitty.game.guard.message.RespChakanShouhu;
import com.kitty.game.guard.service.GuardService;
import com.kitty.game.hunqiao.HunQiaoService;
import com.kitty.game.item.service.PetStoneService;
import com.kitty.game.market.MarketService;
import com.kitty.game.newchoujiang.SendPopMessage;
import com.kitty.game.party.service.PartyService;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.service.BookService;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.player.PlayerService;
import com.kitty.game.rank.service.RankService;
import com.kitty.game.role.message.*;
import com.kitty.game.role.model.Account;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.AccountService;
import com.kitty.game.role.service.PayService;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.server.message.RespOtherLogin;
import com.kitty.game.task.service.NewTaskService;
import com.kitty.game.task.service.taskHandler.DugeonTaskHandler;
import com.kitty.game.task.service.taskHandler.MainTaskHandler;
import com.kitty.game.team.message.RespAroundInfo;
import com.kitty.game.team.message.RespConfirm;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.team.model.AroundInfo;
import com.kitty.game.team.model.Team;
import com.kitty.game.team.service.TeamService;
import com.kitty.game.utils.*;
import com.kitty.game.welfare.service.FirstPayRewardHandler;
import com.kitty.game.welfare.service.ServenDayRewardHandler;
import com.kitty.game.welfare.service.WelfareService;
import com.kitty.game.zhenbao.ZhenbaoService;
import com.kitty.listener.EventDispatcher;
import com.kitty.listener.EventType;
import com.kitty.listener.event.CreateRoleEvent;
import com.kitty.listener.event.FetchEvent;
import com.kitty.listener.event.GatherEndEvent;
import com.kitty.listener.event.HeartBeatEvent;
import com.kitty.common.model.Reason;
import com.kitty.mina.annotation.RequestMapping;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.filter.ModuleCounterFilter;
import com.kitty.mina.message.MessagePusher;
import com.kitty.mina.session.SessionManager;
import com.kitty.mina.session.SessionProperties;
import org.apache.commons.lang3.StringUtils;
import org.apache.mina.core.session.IoSession;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Controller
public class RoleController {
    @Autowired
    PlayerService playerService;

    Logger logger = LoggerFactory.getLogger(RoleController.class);

    /**
     *
     * @param session
     * @param notify
     */
    @RequestMapping
    public void generalNotify(IoSession session, ReqGeneralNotify notify) {
        RoleService roleService = SpringUtils.getBean(RoleService.class);
        int generalType = notify.getType() & 0x0FFFF;//负数变正数
//        logger.error("NotifyModuleCode[{}]",generalType);
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }

        switch (generalType) {
            case NotifyModules.NOTIFY_REQUEST_REBATE_INFO:{
                SendPopMessage respGeneralNotify = new SendPopMessage();
                String message = "WuxtRuleDlg";
                respGeneralNotify.setName(message);
                respGeneralNotify.setType((byte)2);
                MessagePusher.pushMessage(role, respGeneralNotify);
                break;
            }
            case NotifyModules.NOTIFY_BAXIAN_ENTER:{
//                if(SpringUtils.getBean(TeamService.class).isInTeam(role)){
//
//                    return ;
//                }
                int remainCount = SpringUtils.getActivityService().getRemainCount(role, ActivityType.baxian_activity);
                if(remainCount <= 0){
                    MessagePusher.pushMessage(session, new RespMsg("没有扫荡八仙次数。"));
                    return ;
                }

                RespGeneralNotify respGeneralNotify2 = new RespGeneralNotify();
                respGeneralNotify2.setNotify((short) NotifyModules.NOTIFY_OPEN_DLG); //打开对话框
                respGeneralNotify2.setValue("EightImmortalsDlg");
                MessagePusher.pushMessage(role, respGeneralNotify2);
                RespBaxianMengJingInfo respBaxianMengJingInfo =new RespBaxianMengJingInfo();
                respBaxianMengJingInfo.setIndex((byte)(role.getExtendBox().getBaxianIndex()-1));
                respBaxianMengJingInfo.setTimes((short)0);

                respBaxianMengJingInfo.setCurCheckPoint((short)(role.getExtendBox().getBaxianIndex()-1));

                respBaxianMengJingInfo.setMainState((byte) 0);
                respBaxianMengJingInfo.setOpenMax((short) 9);
                respBaxianMengJingInfo.setIsOpenDlg((byte) 1);
                respBaxianMengJingInfo.setEnterNightmare((byte) 0);
                respBaxianMengJingInfo.setIsSweep((byte) 1);
                MessagePusher.pushMessage(role, respBaxianMengJingInfo);
                SpringUtils.getActivityService().addFinishCount(role, ActivityType.baxian_activity, 1);
                if(role.getExtendBox().getBaxianIndex() == 9){
                    role.getExtendBox().setBaxianIndex(1);
                }else{
                    role.getExtendBox().setBaxianIndex(role.getExtendBox().getBaxianIndex()+1);
                }
                SpringUtils.getBean(FightService.class).sendBossExtReward(role,200);
                break;
            }
            case NotifyModules.NOTIFY_DELETE_CHAR:{ //删除角色
                RespConfirm respConfirm = new RespConfirm();
                String confirmMsg = MessageFormat.format("你确定要删除角色#R{0}#n吗？删除后无法恢复。", role.getName());
                respConfirm.setTips(confirmMsg);
                respConfirm.setPara_str("{}");
                role.setConfirm(new DeleteRoleConfirm());
                MessagePusher.pushMessage(role, respConfirm);
                logger.error("删除角色=={}", role.getName());
                break;
            }
            case NotifyModules.DELETE_GODBOOK_SKILL: {//取出天书
                SpringUtils.getBean(BookService.class).takeOutBook(role, notify);
                break;
            }
            case NotifyModules.NOTIFY_LOOK_PLAYER_EQUIP: //查看玩家装备
                /**目标区服不是当前服时，返回关闭装备*/
                if (!SpringUtils.getBean(ServerService.class).getServer().getName().equals(notify.getString())) {
                    MessagePusher.pushMessage(session, new RespMsg("目标玩家已关闭装备查看。"));
                    return ;
                }

                roleService.checkRoleInfo(role, notify);
                break;
            case NotifyModules.NOTICE_FETCH_BONUS:
                /**产生一个领取宠物事件*/
                EventDispatcher.getInstance().fireEvent(new FetchEvent(EventType.FETCH, role, FetchEvent.FETCH_PET));
                break;
            case NotifyModules.NOTIFY_RANK_GET_EQUIP: {
                SpringUtils.getBean(RankService.class).info(role, notify);
                break;
            }
            case NotifyModules.NOTIFY_SHOW_RANK_PET: {
                SpringUtils.getBean(RankService.class).petInfo(role, notify);
                break;
            }
            case NotifyModules.NOTIFY_RECHARGE_COIN: //充值
                SpringUtils.getBean(PayService.class).createPayInfo(session, role, notify);
                break;
            case NotifyModules.DROP_TASK:  //放弃任务
                SpringUtils.getBean(NewTaskService.class).requestGiveUpTask(role, notify.getStatus());
                break;
            case NotifyModules.GET_RANK_INFO:  //打开排行榜
                if (session.getAttribute("paihangbangpaihangbangpaihangbangpaihangbangpaihangbang") ==null){
                    session.setAttribute("paihangbangpaihangbangpaihangbangpaihangbangpaihangbang",System.currentTimeMillis());
                    SpringUtils.getBean(RankService.class).pushRankInfo(role, notify);
                }else {
                    Long old = (Long) session.getAttribute("paihangbangpaihangbangpaihangbangpaihangbangpaihangbang");
                    if (System.currentTimeMillis() - old <1000){
                        MessagePusher.pushMessage(role,new RespNotifyMiscEx("刷新太快了！！"));
                        return;
                    }
                    session.setAttribute("paihangbangpaihangbangpaihangbangpaihangbangpaihangbang",System.currentTimeMillis());
                    SpringUtils.getBean(RankService.class).pushRankInfo(role, notify);
                }
                break;
            case NotifyModules.CHAR_RENAME:  //改名
                roleService.modifyName(role, notify.getStatus());
                break;
            case NotifyModules.NOTIFY_CHAR_CHANGE_SEX:  //改性别
                roleService.modifySex(role);
                break;
            case NotifyModules.GET_RECOMMEND_POLAR: { //打开自动相性设置界面
                Map<String, Byte> nutMap = role.getExtendBox().getAutoPolar();
                RespAutoXiangxing respAutoXiangxing = new RespAutoXiangxing();
                respAutoXiangxing.setOne((byte) nutMap.get("one"));
                respAutoXiangxing.setTwo((byte) nutMap.get("two"));
                respAutoXiangxing.setThere((byte) nutMap.get("there"));
                respAutoXiangxing.setStatus((byte) nutMap.get("status"));
                respAutoXiangxing.setType((byte) nutMap.get("type"));
                MessagePusher.pushMessage(session, respAutoXiangxing);
                break;
            }
            case NotifyModules.GET_RECOMMEND_ATTRIB: { //打开自动加点设置界面
                int id = 0;
                if (!Strings.isEmpty(notify.getStatus())) {
                    id = Integer.parseInt(notify.getStatus());
                }
                Map<String, Byte> nutMap = null;
                if (id >= 1) {
                    //返回宠物设置
                    Pet pet = role.getPetBox().getPetByPetId(id);
                    if (pet == null) {
                        return;
                    }
                    nutMap = pet.getAutoAtrrib();
                } else {
                    id = role.getRoleId();
                    //返回人物设置
                    nutMap = role.getExtendBox().getAutoAttrib();
                }

                RespAutoShuxing respAutoShuxing = new RespAutoShuxing();
                respAutoShuxing.setLiliang(nutMap.get("str"));
                respAutoShuxing.setLingli(nutMap.get("wiz"));
                respAutoShuxing.setMinjie(nutMap.get("dex"));
                respAutoShuxing.setTizhi(nutMap.get("con"));
                respAutoShuxing.setStatus(nutMap.get("status"));
                respAutoShuxing.setType(nutMap.get("type"));
                MessagePusher.pushMessage(session, respAutoShuxing);
                break;
            }
            case NotifyModules.NOTIFY_START_AUTO_FIGHT: {//开启自动战斗
                FightService fightService = SpringUtils.getBean(FightService.class);
                role.setAutoFight(Byte.parseByte(notify.getStatus()));
                RespUpdate respUpdate = new RespUpdate();
                respUpdate.setRoleId(role.getRoleId());
                respUpdate.setList(Collections.singletonList(new FiedValue(307, role.getAutoFight())));
                MessagePusher.pushMessage(session, respUpdate);

                Fight fight = fightService.getFightByRoleId(role.getRoleId());
                if (fight == null || fight.isOver()) {
                    return;
                }
                SpringUtils.getBean(FightExecutorService.class).addFightTask(fight, () -> roleService.openAutoFight(role, fight));
                break;
            }
            case NotifyModules.NOTIFY_TTT_JISU_FEISHENG:
                //  通天塔急速飞升  元宝
                SpringUtils.getBean(TowerTaskHandler.class).flyUp(role, Const.FLY_UP_TYPE_USING_GOLD, Integer.parseInt(notify.getStatus()));
                break;
            case NotifyModules.NOTIFY_TTT_KUAISU_FEISHENG:
                //  通天塔快速飞升 金钱
                SpringUtils.getBean(TowerTaskHandler.class).flyUp(role, Const.FLY_UP_TYPE_USING_MONEY, Integer.parseInt(notify.getStatus()));
                break;
            case NotifyModules.NOTIFY_TTT_LEAVE_TOWER:
                // 通天塔离开
                SpringUtils.getBean(TowerTaskHandler.class).leave(role);
                break;
            case NotifyModules.NOTIFY_TTT_GO_NEXT_LAYER:
                // 下一层
                SpringUtils.getBean(TowerTaskHandler.class).enterNextLayer(role, null);
                break;
            case NotifyModules.NOTIFY_OPEN_STORE: //打开仓库??
                if (notify.getStatus().equals("1") && notify.getString().equals("1")) {
                    logger.info("打开仓库操作");
                    BagService bagService = SpringUtils.getBean(BagService.class);
                    bagService.sendNullStore(role);
                    for (Map.Entry<Integer, RoleEquip> entry : role.getEquipBox().getEquips().entrySet()) {
                        RoleEquip roleEquip = entry.getValue();
                        if (roleEquip.getPosition() >= 201 && roleEquip.getPosition() < 326) {
                            bagService.sendOneStore(roleEquip.getPosition(), role, roleEquip);
                        }
                    }
                } else if (notify.getStatus().equals("2")) {//打开宠物仓库
                    PetService petService = SpringUtils.getBean(PetService.class);
                    petService.sendPetStore(role);
                }else if (notify.getStatus().equals("9")){
                    SpringUtils.getBean(HunQiaoService.class).openHunQiaoStore(role);
                }

                break;
            case NotifyModules.NOTICE_QUERY_CARD_INFO:  //查看装备
                if (!notify.getStatus().contains("=")) {
                    SpringUtils.getBean(ChatService.class).checkItemInfo(session, notify.getStatus());
                } else if (StringUtils.isNotEmpty(notify.getString())){
                    //集市和珍宝
                    String[] statusArray = notify.getStatus().split("=");
                    String type = statusArray[0];
                    switch (type) {
                        case "集市":
                            SpringUtils.getBean(MarketService.class).viewMarketCard(role, notify.getStatus(), notify.getString());
                            break;
                        case "珍宝":
                            SpringUtils.getBean(ZhenbaoService.class).viewZhenbaoCard(role, notify.getStatus(), notify.getString());
                            break;
                    }
                }

                break;
            case NotifyModules.NOTIFY_DO_DAILY_SIGN:
                // 签到
                SpringUtils.getBean(WelfareService.class).sign(role);
                break;
            case NotifyModules.NOTIFY_OPEN_SHENMI_DALI:
//                RespShenmiGift respShenmiGift = new RespShenmiGift();
//                respShenmiGift.setOnline_time(10);
//                MessagePusher.pushMessage(role, respShenmiGift);
                // 神秘大礼
                break;
            case NotifyModules.NOTIFY_OPEN_NEWBIE_GIFT: {
                // 新手礼包
                WelfareService welfareService = SpringUtils.getBean(WelfareService.class);
                welfareService.newcomerList(role);
                break;
            }
            case NotifyModules.NOTIFY_FETCH_NEWBIE_GIFT: {
                // 领取新手礼包
                WelfareService welfareService = SpringUtils.getBean(WelfareService.class);
                welfareService.getNewcomerGift(notify,role);
                break;
            }
            case NotifyModules.NOTIFY_OPEN_DAILY_SIGN:
                // 每日签到
                SpringUtils.getBean(WelfareService.class).dailySign(role);
                break;
            case NotifyModules.NOTIFY_OPEN_WELFARE:
                // 打开福利
                SpringUtils.getBean(WelfareService.class).openWelfare(session, notify);
                break;
            case NotifyModules.NOTIFY_SET_USE_MONEY_TYPE: {//切换使用代金券
                List<FiedValue> list = new ArrayList<>();
                FiedValue fiedValue = new FiedValue();
                list.add(fiedValue);
                {
                    fiedValue.setType((short) 310);
                    fiedValue.setVT((byte) 1);
                    fiedValue.setValue(Byte.parseByte(notify.getStatus()));
                }
                RespUpdate respUpdate = new RespUpdate();
                respUpdate.setRoleId(role.getRoleId());
                respUpdate.setList(list);
                MessagePusher.pushMessage(session, respUpdate);
                role.setUseVoucher(notify.getStatus().equals("1"));


                break;
            }
            case NotifyModules.NOTIFY_GUARD_BASIC_ATTRI: {//查看守护属性
                String guardName = notify.getStatus();
                GuardSet guardSet = SpringUtils.getGuardService().getGuardSet(guardName);//Json.fromJson(GuardSet.class, content);
                if (guardSet == null) {
                    return;
                }
                logger.info("守护信息==={}", Json.toJson(guardSet));
                List<FiedValue> list = FieldUtils.guardPanelInfo(guardSet, role.getLevel(), null);
                RespChakanShouhu respChakanShouhu = new RespChakanShouhu();
                respChakanShouhu.setList(list);
                MessagePusher.pushMessage(session, respChakanShouhu);

                break;
            }
            case NotifyModules.CALL_GUARD: //召唤守护
                GuardService guardService = SpringUtils.getBean(GuardService.class);
                guardService.buyGuard(session, notify);
                break;
            case NotifyModules.GUARD_USE_SKILL_D:  // 跟换守护策略
                SpringUtils.getBean(GuardService.class).chargeSkillType(role, notify);
                break;
            case NotifyModules.NOTIFY_REQUEST_GUARD_ID:
                // 客户端请求正在历练的守护
                break;
            case NotifyModules.NOTIFY_CLIENT_STATUS:
                //客户端状态，如未激活、已激活但长时间无输入、正常等
                session.setAttribute(SessionProperties.CLIENT_STATUS, notify.getStatus());
                {
                    RespUpdate respUpdate = new RespUpdate();
                    respUpdate.setRoleId(role.getRoleId());
                    respUpdate.setList(new ArrayList<>());
                    NutMap propsStatus = role.getPropsStatus();
                    respUpdate.getList().add(new FiedValue(192, propsStatus.getInt("roleStatus", 0)));
                    MessagePusher.pushMessage(role,respUpdate);
                }
                //客户端切换后台
                try {

                    if (session.getAttribute("qiehuanhoutaiqiehuanhoutaiqiehuanhoutai")== null){
                        ArrayList<Long> arrayList = new ArrayList<>();
                        arrayList.add(System.currentTimeMillis());
                        session.setAttribute("qiehuanhoutaiqiehuanhoutaiqiehuanhoutai",arrayList);
                    }else {
                        ArrayList<Long> arrayList = (ArrayList<Long>) session.getAttribute("qiehuanhoutaiqiehuanhoutaiqiehuanhoutai");
                        arrayList.add(System.currentTimeMillis());
                        if (arrayList.size() >10){
                            ArrayList<Long> temp = new ArrayList(arrayList);
                            if (System.currentTimeMillis()-temp.get(0)<1*60*1000){
                                logger.error("服务器检测到异常==={}=={}",role.getUid(),role.getName());
                                for (int i=0;i<10;i++){
                                    MessagePusher.pushMessage(session, new RespNotifyMiscEx("#R服务器检测到异常,3秒后将强制下线!!!"));
                                }
//                                SpringUtils.getBean(PkService.class).add2Prison(role);
                                ScheduledFuture<?> timeOutTask = SchedulerManager.getInstance().schedule(new Runnable() {
                                    @Override
                                    public void run() {
                                        logger.error("加速器断开连接=={}",role.getName());
                                        session.closeNow();
                                    }
                                }, 3000);
                                return;
                            }
                            arrayList = new ArrayList<>();
                            arrayList.add(System.currentTimeMillis());
                            session.setAttribute("qiehuanhoutaiqiehuanhoutaiqiehuanhoutai",arrayList);
                        }
                    }
                }catch (Exception e){

                }

            break;
            case NotifyModules.NOTIFY_SET_COMBAT_GUARD:
                //队伍中加入守护  设置参战守护 Todo 以后再写
                SpringUtils.getBean(GuardService.class).fightStatus(role, Integer.parseInt(notify.getStatus()),(byte)1,Integer.parseInt(notify.getString()));
                break;
            case NotifyModules.NOTIFY_BUY_INSIDER: {//购买VIP
                String vipType = notify.getStatus();
                int price = 0;
                String buyType = "";
                switch (vipType) {
                    case "1": //月卡
                        price = 3000;
                        buyType = "月卡";
                        break;
                    case "2": //季卡
                        price = 9000;
                        buyType = "季卡";
                        break;
                    case "3": //年卡
                        price = 36000;
                        buyType = "年卡";
                        break;
                }
                if (role.getGold() >= price) {
                    role.setConfirm(new BuyVipConfirm(price));
                    RespConfirm respConfirm = new RespConfirm();
                    respConfirm.setTips("是否确认购买位列仙班·" + buyType + "？#r（#R剩余的位列仙班天数会累加#n）");
                    MessagePusher.pushMessage(role, respConfirm);
                }
                break;
            }
            case NotifyModules.NOTIFY_STALL_REMOVE_GOODS:
                // 集市下架物品
                SpringUtils.getBean(MarketService.class).removeGoods(session, notify);
                break;
            case NotifyModules.NOTIFY_DRAW_INSIDER_COIN: {//会员领取每日福利
                int currTime = new Long(new Date().getTime() / 1000).intValue();
                long expireTime = role.getExpireTime() < 0 ? role.getExpireTime() + 4294967296L : role.getExpireTime();
                int vipLevel = Integer.parseInt(notify.getStatus());
                if (role.isReceive()) {
                    return;
                }
                int receiveSiver = 0;
                if (vipLevel == 1 && role.getVipType() == vipLevel && expireTime >= currTime) {
                    receiveSiver = 100;
                } else if (vipLevel == 2 && role.getVipType() == vipLevel && expireTime >= currTime) {
                    receiveSiver = 120;
                } else if (vipLevel == 3 && role.getVipType() == vipLevel && expireTime >= currTime) {
                    receiveSiver = 150;
                } else {
                    return;
                }
                role.setReceive(true);
                roleService.addSiver(role, receiveSiver, Reason.DRAW_INSIDER_COIN);

                roleService.updateRoleGoldAndSiver(role);

                RespNotifyMiscEx respNotifyMiscEx = new RespNotifyMiscEx();
                respNotifyMiscEx.setMsg("你领取了#R" + receiveSiver + "#n银元宝。");
                respNotifyMiscEx.setTime(new Long(new Date().getTime() / 1000).intValue());
                MessagePusher.pushMessage(session, respNotifyMiscEx);

                RespVipStatus RespVipStatus = new RespVipStatus(); //会员状态

                RespVipStatus.setType(role.getVipType());
                RespVipStatus.setExpireTime(role.getExpireTime());
                RespVipStatus.setReceive(role.isReceive());
                MessagePusher.pushMessage(session, RespVipStatus);

                MessagePusher.pushMessage(session, new RespIconCartoon("银元宝"));
                break;
            }
            case NotifyModules.NOTIFY_FAST_ADD_EXTRA: {
                //金钱补充 补充储备
                int roleMoney = role.getMoney();
                int voucher = role.getVoucher();
                int price = 0;
                String type ="代金券";
                String successMessage ="你花费了{0}文{1}#n，{2}增加#R{3}#n点。";
                String successTips ="{0}增加#R{1}#n点。";
                switch (notify.getStatus()) {
                    case "1": {
                        //气血储备 价格 120000
                        price = 120000;
                        if(voucher<price){
                            if (roleMoney < price) {
                                RespMsg respMsg = new RespMsg();
                                respMsg.setMsg("你的金钱不足！请到积分商城购买");
                                MessagePusher.pushMessage(session, respMsg);
                                return;
                            }else {
                                type ="金钱";
                                roleService.subtractMoney(role,  price);
                            }
                        }else {
                            role.setVoucher(role.getVoucher() - price);
                        }
                        role.setCurrLife(role.getMaxLife());
                        int saveQixue = role.getSaveLife() + 300000;
                        if (saveQixue > 900000000) {
                            saveQixue = 900000000;
                        }
                        role.setSaveLife(saveQixue);
                        MessagePusher.pushMessage(session,new RespMsg(MessageFormat.format(successTips,"气血储备",300000)));
                        MessagePusher.pushMessage(session,new RespNotifyMiscEx(MessageFormat.format(successMessage,AsktaoUtil.getMoneyFormat(price),type,"气血储备",300000)));
                        break;
                    }
                    case "2": {
                        //法力储备 价格 360000
                        price = 360000;
                        if(voucher<price){
                            if (roleMoney < price) {
                                RespMsg respMsg = new RespMsg();
                                respMsg.setMsg("你的金钱不足！请到积分商城购买。");
                                MessagePusher.pushMessage(session, respMsg);
                                return;
                            }else {
                                type ="金钱";
                                roleService.subtractMoney(role, price, Reason.BUY_ITEM);
                            }
                        }else {
                            role.setVoucher(role.getVoucher() - price);
                        }

                        role.setCurrMana(role.getMaxMana());
                        int saveFali = role.getSaveMana() + 300000;
                        if (saveFali > 900000000) {
                            saveFali = 900000000;
                        }
                        role.setSaveMana(saveFali);
                        MessagePusher.pushMessage(session,new RespMsg(MessageFormat.format(successTips,"法力储备",300000)));
                        MessagePusher.pushMessage(session,new RespNotifyMiscEx(MessageFormat.format(successMessage,AsktaoUtil.getMoneyFormat(price),type,"法力储备",300000)));
                        break;
                    }
                    case "3": {
                        //忠诚储备 价格 1800000
                        price = 1800000;
                        if(voucher<price){
                            if (roleMoney < price) {
                                RespMsg respMsg = new RespMsg();
                                respMsg.setMsg("你的金钱不足！请到积分商城购买");
                                MessagePusher.pushMessage(session, respMsg);
                                return;
                            }else {
                                type ="金钱";
                                roleService.subtractMoney(role,  price);
                            }
                        }else {
                            role.setVoucher(role.getVoucher() - price);
                        }
                        int saveLoyalty = role.getSaveLoyalty() + 300;
                        if (saveLoyalty > 3000000) {
                            saveLoyalty = 3000000;
                        }
                        role.setSaveLoyalty(saveLoyalty);
                        MessagePusher.pushMessage(session,new RespMsg(MessageFormat.format(successTips,"忠诚储备",300)));
                        MessagePusher.pushMessage(session,new RespNotifyMiscEx(MessageFormat.format(successMessage,AsktaoUtil.getMoneyFormat(price),type,"忠诚储备",300)));
                        break;
                    }

                }
                //更新角色金钱
                roleService.updateRoleMoney(role);
                //刷新角色信息
                roleService.sendExtraAttribute(role);
                break;
            }
            case NotifyModules.NOTIFY_QUERY_TEAM_INFO: //查询周围玩家/队伍信息  参数"around_player"   "around_team"
                TeamService teamService = SpringUtils.getBean(TeamService.class);
                String type = notify.getStatus();
                boolean isTeam = false;
                if ("around_team".equals(type)) {//周围队长
                    isTeam = true;
                }
                RespAroundInfo respAroundInfo = new RespAroundInfo();
                respAroundInfo.setType("csc_" + type);
                List<AroundInfo> infoList = teamService.getAroundInfo(role, isTeam);
                respAroundInfo.setList(infoList);
                MessagePusher.pushMessage(session, respAroundInfo);
                break;
            case NotifyModules.NOTIFY_RANK_ME_INFO: //返回排行榜个人信息
                // 排行榜
                SpringUtils.getBean(RankService.class).rankMeInfo(role);
                break;
            case NotifyModules.NOTIFY_OPEN_EXORCISM: {//开驱魔香
                SpringUtils.getFightService().openAvoidMonster(role);
                break;
            }
            case NotifyModules.NOTIFY_CLOSE_EXORCISM: {//关驱魔香
                SpringUtils.getFightService().closeAvoidMonster(role);
                break;
            }
            case NotifyModules.NOTIFY_GET_LIVENESS_INFO:
                RespLivenessInfo respLivenessInfo = SpringUtils.getActivityService().getRespLivenessInfo(role);
                MessagePusher.pushMessage(session, respLivenessInfo);
                break;
            case NotifyModules.NOTIFY_FETCH_LIVENESS_BONUS:
                SpringUtils.getActivityService().fetchLivenessReward(role, Integer.parseInt(notify.getStatus()));
                break;
            case NotifyModules.NOTICE_COMBAT_STATUS_INFO: //查看战斗增益属性
                SpringUtils.getBean(FightService.class).checkExtraInfo(role, notify);
                break;
            case NotifyModules.NOTIFY_STALL_TAKE_CASH:
                // 集市提款
                SpringUtils.getBean(MarketService.class).takeCash(role);
                break;
            case NotifyModules.NOTIFY_STALL_BAITAN_TRANSACTION_RECORD:
                SpringUtils.getBean(MarketService.class).queryTransactionRecord(role);
                break;
            case NotifyModules.NOTIFY_OPEN_MY_STALL:
                // 打开摆摊
                SpringUtils.getBean(MarketService.class).sendGoodsList(role);
                break;
            case NotifyModules.NOTIFY_STALL_RESTART_GOODS:
                // 重新上摊位
                SpringUtils.getBean(MarketService.class).upShellAgain(role, notify);
                break;
            case NotifyModules.NOTIFY_STALL_QUERY_PRICE:
                //查询物品价格
                SpringUtils.getBean(MarketService.class).getGoodsPrice(notify.getStatus(), role);
                break;
            case NotifyModules.NOTIFY_SET_LOCK_EXP: {//锁定经验
                int currTime = new Long(new Date().getTime() / 1000).intValue();
                if (!role.isVip()) {
                    return;
                } else {
                    String para = notify.getString();
                    int needMoney = 0;
                    if (para.equals("1")) {//锁定经验
                        needMoney = 5000000;
                    } else {//解锁经验
                        needMoney = 3200000;
                    }
                    int DBMoney = role.getMoney();
                    if (DBMoney < needMoney) {
                        return;
                    }
                    roleService.subtractMoney(role,  needMoney);
                    int id = Integer.parseInt(notify.getStatus());
                    if (id >= 1) {//宠物
                        Pet pet = role.getPetBox().getPetByPetId(id);
                        pet.setLockexp(para.equals("1"));
                        role.save();
                        
                        List<FiedValue> list = new ArrayList<>();
                        FiedValue fiedValue = new FiedValue();
                        fiedValue.setType((short) 311);
                        fiedValue.setVT((byte) 1);
                        fiedValue.setValue(Byte.parseByte(notify.getString()));
                        list.add(fiedValue);
                        RespUpdate respUpdate = new RespUpdate();
                        respUpdate.setRoleId(pet.getId());
                        respUpdate.setList(list);
                        MessagePusher.pushMessage(session, respUpdate);
                        MessagePusher.pushMessage(session, new RespNotifyMiscEx("你花费" + AsktaoUtil.getMoneyFormat(needMoney) + "#n文钱,对#R" + pet.getNickname() + "#n经验进行了" + (pet.isLockexp() ? "加锁" : "解锁")));
                    } else {//人物
                        logger.error("解锁经验=={}=={}",role.getRoleId(),role.getName());
                        roleService.substractChargeScore(role,20);
                        role.setLockexp(para.equals("1"));
                        role.save();

                        List<FiedValue> list = new ArrayList<>();
                        FiedValue fiedValue = new FiedValue();
                        fiedValue.setType((short) 311);
                        fiedValue.setVT((byte) 1);
                        fiedValue.setValue(Byte.parseByte(notify.getString()));
                        list.add(fiedValue);
                        RespUpdate respUpdate = new RespUpdate();
                        respUpdate.setRoleId(role.getRoleId());
                        respUpdate.setList(list);
                        MessagePusher.pushMessage(session, respUpdate);
                        MessagePusher.pushMessage(session, new RespNotifyMiscEx("你花费" + AsktaoUtil.getMoneyFormat(needMoney) + "#n文钱,对人物经验进行了" + (role.isLockexp() ? "加锁。" : "解锁。")));
                    }
                }
                break;
            }
            case NotifyModules.NOTIFY_OPEN_STALL_LIST:
                // 集市列表
                SpringUtils.getBean(MarketService.class).marketQuery(notify, session);
                break;
            case NotifyModules.SELL_ITEM: //出售背包装备
                SpringUtils.getBean(EquipService.class).soldToSystem(role, Short.parseShort(notify.getStatus()), Short.parseShort(notify.getString()));
                break;
            case NotifyModules.NOTIFY_SHUADAO_OPEN_INTERFACE: {//打开刷道界面
                SpringUtils.getBean(ShuaDaoTaskHandler.class).pushRespOpenShuadaoDlg(role);
                SpringUtils.getBean(ShuaDaoTaskHandler.class).pushShuaDaoPropsStatus(role);

                //返回如意刷道令状态
                RespRuyiStatus respRuyiStatus = new RespRuyiStatus();
                respRuyiStatus.setStatus(role.getPropsStatus().getBoolean("ruyiStatus", false));
                MessagePusher.pushMessage(session, respRuyiStatus);

                RespShuadaoUsePointStatus respShuadaoUsePointStatus = new RespShuadaoUsePointStatus();
                MessagePusher.pushMessage(session, respShuadaoUsePointStatus);

                roleService.sendShuadaoStauts(role);


//                String msg = "开启三倍刷道消耗增加三倍:#R获取双倍道行*3#n\n" +
//                        "开启五倍刷道消耗增加五倍:#R获取双倍道行*5#n\n" +
//                        "没有消耗时自动变成初始刷道奖励\n" +
//                        "开启离线刷道时如果开启的是三倍刷道消耗增加三倍:#R获取双倍道行*3#n\n" +
//                        "开启离线刷道时如果开启的是五倍刷道消耗增加五倍:#R获取双倍道行*5#n\n" +
//                        "没有消耗时自动变成初始刷道奖励";
//                role.setConfirm(new OfflineConfirm(msg));
//                RespConfirm respConfirm = new RespConfirm();
//                respConfirm.setTips(msg);
//                MessagePusher.pushMessage(role, respConfirm);
                break;
            }
            case NotifyModules.NOTIFY_SHUADAO_BUY_OFFLINE_TIME: {//购买离线刷道时间
                //String msg = "确认花费#R100积分#n购买#R90分钟#n离线刷道时间吗？";
                String msg = "暂时关闭离线刷到功能";
                MessagePusher.pushMessage(role,new RespNotifyMiscEx(msg));
//                role.setConfirm(new OfflineTimeConfirm(msg));
//                RespConfirm respConfirm = new RespConfirm();
//                respConfirm.setTips(msg);
//                MessagePusher.pushMessage(role, respConfirm);
                break;
            }
            case NotifyModules.NOTIFY_SHUADAO_DO_BONUS: {
                //领取奖励
                long round = role.getOfflineNotice().getRound();
                int lastRound = roleService.getLastRound(role);
                int costround = (int) (round - lastRound);
                NutMap nutMap =role.getPropsStatus();
                if (nutMap != null) {
                    int point = role.getPropsStatus().getInt("role");
                    // 超级仙风散
                    if (nutMap.getInt("roleStatus") == 1 ) {
                        if (point < 4 * costround){
                            role.setConfirm(new OfflineRewardConfirm("双倍超级仙风散点数不足，确认领取离线奖励"));
                            String msg = "#R双倍超级仙风散点数不足，确认领取离线奖励#n？";
                            RespConfirm respConfirm = new RespConfirm();
                            respConfirm.setTips(msg);
                            MessagePusher.pushMessage(role, respConfirm);
                            return;
                        }
                    }
                    roleService.offlineReward(role);
                    logger.error("领取离线奖励=={}=={}=={}=={}=={}=round={}", role.getRoleId(), role.getName(), costround, Json.toJson(role.getOfflineNotice()),costround);
                    SpringUtils.getBean(ShuaDaoTaskHandler.class).add(nutMap.getInt("daohang", 0) * costround
                            , nutMap.getInt("qianneng", 0) * costround
                            , nutMap.getInt("money", 0) * costround
                            , nutMap.getInt("petWuxue", 0) * costround
                            , nutMap.getInt("size", 0) * costround
                            , role,costround);
                }
                role.getOfflineNotice().setLeijiTime(0);
                role.getOfflineNotice().setRound(lastRound);
                int ten = SpringUtils.getBean(ShuaDaoTaskHandler.class).getTenShuaDaoUsedTime(role, role.getOfflineNotice().getActivityType());
                ten = ten / 10;
                int lasttime = role.getOfflineNotice().getOfflineTime() - costround * ten;

                role.getOfflineNotice().setOfflineTime(lasttime <= 0 ? 0 : lasttime);
                role.save();
                roleService.sendShuadaoStauts(role);
                logger.error("每轮时间=={}=={}=={}={}={}", ten, lastRound, lasttime, lastRound, Json.toJson(role.getOfflineNotice()));
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("领取离线刷道奖励成功"));
                break;
            }
            case NotifyModules.NOTIFY_SHUADAO_SET_OFFLINE: {//开启或者关闭离线刷道
        //       break;
                logger.error("开启或者关闭离线刷道=={}",Json.toJson(notify));
                // 能否开启离线刷道
                String status = notify.getStatus();
                String[] ss = status.split(";");
                int round = Integer.parseInt(ss[1]);
                int state = Integer.parseInt(ss[0]);
                int ten = SpringUtils.getBean(ShuaDaoTaskHandler.class).getTenShuaDaoUsedTime(role, role.getOfflineNotice().getActivityType());
                ten = ten / 10;
                if (round * ten >  role.getOfflineNotice().getOfflineTime()){
                    MessagePusher.pushMessage(role,new RespNotifyMiscEx("购买的离线时间不足"));
                    return;
                }
                role.getOfflineNotice().setRound(round);
                if (state <= 0){
                    role.getOfflineNotice().setShuadao(0);
                }else {
                    role.getOfflineNotice().setShuadao(1);

                }
                if (role.getOfflineNotice().getShuadao() == 1){
                    //重新开启离线刷道，清空之前的时间
                    role.getOfflineNotice().setLastTime(System.currentTimeMillis());
                }
                int shuadaoLevel = role.getPropsStatus().getInt("shuadao_state", 0);
                if(shuadaoLevel == 2){
                    if (status.contains("降妖")){
                        role.getOfflineNotice().setActivityType(ActivityType.SHUA_DAO_XIANGYAO_TASK2);
                    }else if (status.contains("伏魔")){
                        role.getOfflineNotice().setActivityType(ActivityType.SHUA_DAO_FUMO_TASK2);
                    }else if (status.contains("飞仙")){
                        role.getOfflineNotice().setActivityType(ActivityType.SHUA_DAO_FEIXIANDUXIE_TASK2);
                    }
                }else{
                    if (status.contains("降妖")){
                        role.getOfflineNotice().setActivityType(ActivityType.SHUA_DAO_XIANGYAO_TASK);
                    }else if (status.contains("伏魔")){
                        role.getOfflineNotice().setActivityType(ActivityType.SHUA_DAO_FUMO_TASK);
                    }else if (status.contains("飞仙")){
                        role.getOfflineNotice().setActivityType(ActivityType.SHUA_DAO_FEIXIANDUXIE_TASK);
                    }
                }
                role.save();
                roleService.sendShuadaoStauts(role);
                NutMap nutMap = role.getPropsStatus();
               if (nutMap.getInt("roleStatus") == 1){
                    MessagePusher.pushMessage(role,new RespNotifyMiscEx("当前是#R双倍刷道"));
                }
                if (role.getOfflineNotice().getShuadao() == 0){
                    MessagePusher.pushMessage(role,new RespNotifyMiscEx("已经关闭离线刷道"));
                }else {
                    MessagePusher.pushMessage(role,new RespNotifyMiscEx("已经开启离线刷道"));
                }
                break;
            }
            case NotifyModules.NOTIFY_BUY_DOUBLE_POINTS: {//购买双倍 108元宝
//                if (true){
//                    MessagePusher.pushMessage(role,new RespNotifyMiscEx("双倍维护中"));
//                    return;
//                }
                int num =0;
                try {
                    num = Integer.parseInt(notify.getStatus());
                }catch (Exception e){
                    session.closeNow();
                }
                if (num <= 0) {
                    return;
                }
                if (num >10000){
                    return;
                }
                int DBSiver = role.getSiver();
                if (DBSiver < 108 * num) {
                    int DBGold = role.getGold();
                    if (DBGold < 108 * num) {
                        MessagePusher.pushMessage(session, new RespMsg("你的元宝不足。"));
                        return;
                    } else {
                        SpringUtils.getRoleService().subtractGold(role, 108 * num, Reason.BUY_DOUBLE_POINTS);
                        NutMap nutMap = role.getPropsStatus();
                        nutMap.setv("role", nutMap.getInt("role", 0) + 200 * num);
                        role.setPropsStatus(nutMap);
                        MessagePusher.pushMessage(session, new RespNotifyMiscEx("你花费了#R" + 108 * num + "#n金元宝，增加了#R" + 200 * num + "#n点超级仙风散点数，当前剩余#R" + nutMap.getInt("role") + "#n点。"));
                    }
                } else {
                    roleService.subtractSiver(role, 108 * num, Reason.BUY_DOUBLE_POINTS);
                    NutMap nutMap = role.getPropsStatus();
                    nutMap.setv("role", nutMap.getInt("role", 0) + 200 * num);
                    role.setPropsStatus(nutMap);
                    MessagePusher.pushMessage(session, new RespNotifyMiscEx("你花费了#R" + 108 * num + "#n银元宝，增加了#R" + 200 * num + "#n点超级仙风散点数，当前剩余#R" + nutMap.getInt("role") + "#n点。"));
                }

                roleService.updateRoleGoldAndSiver(role);
                ArrayList<FiedValue> list = new ArrayList<>();
                FiedValue fiedValue = new FiedValue();
                fiedValue.setType((short) 191);
                fiedValue.setVT((byte) 3);
                fiedValue.setValue(role.getPropsStatus().getInt("role"));
                list.add(fiedValue);
                RespUpdate respUpdate = new RespUpdate();
                respUpdate.setRoleId(role.getRoleId());
                respUpdate.setList(list);
                MessagePusher.pushMessage(session, respUpdate);

                break;
            }
            case NotifyModules.NOTIFY_BUY_SHENMU_POINTS: {//购买神木鼎 328
                int num = Integer.parseInt(notify.getStatus());
                if (num <= 0) {
                    return;
                }
                if (num >10000){
                    return;
                }
                int DBSiver = role.getSiver();
                if (DBSiver < 328 * num) {
                    int DBGold = role.getGold();
                    if (DBGold < 328 * num) {
                        MessagePusher.pushMessage(session, new RespMsg("你的元宝不足。"));
                        return;
                    } else {
                        SpringUtils.getRoleService().subtractGold(role, 328 * num, Reason.BUY_SHENMU_POINTS);
                        NutMap nutMap = role.getPropsStatus();
                        nutMap.setv("shenmu", nutMap.getInt("shenmu", 0) + 1000 * num);
                        role.setPropsStatus(nutMap);
                        MessagePusher.pushMessage(session, new RespNotifyMiscEx("你花费了#R" + 328 * num + "#n金元宝，增加了#R" + 1000 * num + "#n点神木鼎点数，当前剩余#R" + nutMap.getInt("shenmu") + "#n点。"));
                    }
                } else {
                    roleService.subtractSiver(role, 328 * num, Reason.BUY_SHENMU_POINTS);
                    NutMap nutMap = role.getPropsStatus();
                    nutMap.setv("shenmu", nutMap.getInt("shenmu", 0) + 1000 * num);
                    role.setPropsStatus(nutMap);
                    MessagePusher.pushMessage(session, new RespNotifyMiscEx("你花费了#R" + 328 * num + "#n银元宝，增加了#R" + 1000 * num + "#n点神木鼎点数，当前剩余#R" + nutMap.getInt("shenmu") + "#n点。"));
                }

                roleService.updateRoleGoldAndSiver(role);
                ArrayList<FiedValue> list = new ArrayList<>();
                FiedValue fiedValue = new FiedValue();
                fiedValue.setType((short) 875);
                fiedValue.setVT((byte) 2);
                fiedValue.setValue((short) role.getPropsStatus().getInt("shenmu"));
                list.add(fiedValue);
                RespUpdate respUpdate = new RespUpdate();
                respUpdate.setRoleId(role.getRoleId());
                respUpdate.setList(list);
                MessagePusher.pushMessage(session, respUpdate);
                break;
            }
            case NotifyModules.NOTIFY_ENABLE_DOUBLE_POINTS: {//开关双倍点数
                NutMap nutMap = role.getPropsStatus();
                nutMap.setv("roleStatus", Byte.parseByte(notify.getStatus()));
                role.setPropsStatus(nutMap);


                ArrayList<FiedValue> list = new ArrayList<>();
                FiedValue fiedValue = new FiedValue();
                fiedValue.setType((short) 192);
                fiedValue.setVT((byte) 1);
                fiedValue.setValue((byte) role.getPropsStatus().getInt("roleStatus"));
                list.add(fiedValue);
                RespUpdate respUpdate = new RespUpdate();
                respUpdate.setRoleId(role.getRoleId());
                respUpdate.setList(list);
                MessagePusher.pushMessage(session, respUpdate);

                if (notify.getStatus().equals("1")) {
                    MessagePusher.pushMessage(session, new RespMsg("成功开启双倍点数，部分活动将消耗双倍点数获得双倍奖励。"));
                } else {
                    MessagePusher.pushMessage(session, new RespMsg("成功关闭双倍点数，双倍点数将不再消耗。"));
                }
                //发送奖励

                break;
            }
            case NotifyModules.NOTIFY_ENABLE_SHENMU_POINTS: {//开关神木鼎点数
                NutMap nutMap = role.getPropsStatus();
                nutMap.setv("shenmuStatus", Byte.parseByte(notify.getStatus()));
                role.setPropsStatus(nutMap);


                ArrayList<FiedValue> list = new ArrayList<>();
                FiedValue fiedValue = new FiedValue();
                fiedValue.setType((short) 876);
                fiedValue.setVT((byte) 1);
                fiedValue.setValue((byte) role.getPropsStatus().getInt("shenmuStatus"));
                list.add(fiedValue);
                RespUpdate respUpdate = new RespUpdate();
                respUpdate.setRoleId(role.getRoleId());
                respUpdate.setList(list);
                MessagePusher.pushMessage(session, respUpdate);

                if (notify.getStatus().equals("1")) {
                    MessagePusher.pushMessage(session, new RespMsg("成功开启神木鼎，在练功区域战斗可获得怪物变身卡。"));
                } else {
                    MessagePusher.pushMessage(session, new RespMsg("成功关闭神木鼎，神木鼎点数将不再消耗。"));
                }
                break;
            }
            case NotifyModules.NOTIFY_SHUADAO_SET_ZIQIHONGMENG: {//开关紫气鸿蒙
                NutMap nutMap = role.getPropsStatus();
                nutMap.setv("ziqiStatus", Byte.parseByte(notify.getStatus()));
                role.setPropsStatus(nutMap);


                roleService.sendShuadaoStauts(role);

                if (notify.getStatus().equals("1")) {
                    MessagePusher.pushMessage(session, new RespMsg("你已开启紫气鸿蒙功能。"));
                } else {
                    MessagePusher.pushMessage(session, new RespMsg("你已关闭紫气鸿蒙功能。"));
                }
                break;
            }
            case NotifyModules.NOTIFY_SHUADAO_SET_CHONGFENGSAN: {//开始宠风散
                NutMap nutMap = role.getPropsStatus();
                nutMap.setv("petStatus", Byte.parseByte(notify.getStatus()));
                role.setPropsStatus(nutMap);


                roleService.sendShuadaoStauts(role);

                if (notify.getStatus().equals("1")) {
                    MessagePusher.pushMessage(session, new RespMsg("你已开启宠风散功能。"));
                } else {
                    MessagePusher.pushMessage(session, new RespMsg("你已关闭宠风散功能。"));
                }
                break;
            }
            case NotifyModules.NOTIFY_SHUADAO_SET_JIJI: {//开启急急如律令状态
                NutMap nutMap = role.getPropsStatus();
                nutMap.setv("manguaiStatus", Byte.parseByte(notify.getStatus()));
                role.setPropsStatus(nutMap);


                roleService.sendShuadaoStauts(role);
                if (notify.getStatus().equals("1")) {
                    MessagePusher.pushMessage(session, new RespMsg("你已开启急急如律令功能。"));
                } else {
                    MessagePusher.pushMessage(session, new RespMsg("你已关闭急急如律令功能。"));
                }

                break;
            }
            case NotifyModules.NOTIFY_BUY_ZIQIHONGMENG: {//购买紫气鸿蒙
                /*if (true){
                    MessagePusher.pushMessage(role,new RespNotifyMiscEx("购买紫气鸿蒙维护中"));
                    return;
                }*/
                int num = Integer.parseInt(notify.getString());
                if (num <= 0) {
                    return;
                }
                int delCount = 418 * num;
                if ((role.getGold()+role.getSiver()) < delCount) {
                    MessagePusher.pushMessage(session, new RespMsg("你的元宝不足。"));
                    return;
                }

                int delSiverCount =  role.getSiver() >= delCount ? delCount : role.getSiver();
                if (delSiverCount > 0) {
                    SpringUtils.getRoleService().subtractSiver(role, delSiverCount, Reason.BUY_ZIQIHONGMENG);
                }

                int delGoldCount = delCount > delSiverCount ? delCount - delSiverCount : 0;
                if (delGoldCount > 0) {
                    SpringUtils.getRoleService().subtractGold(role, delGoldCount, Reason.BUY_ZIQIHONGMENG);
                }

                NutMap nutMap = role.getPropsStatus();
                nutMap.setv("ziqi", nutMap.getInt("ziqi", 0) + 200 * num);
                role.setPropsStatus(nutMap);
                role.save();

                StringBuilder delMessage = new StringBuilder();
                if (delSiverCount > 0) {
                    delMessage.append("#R" + delSiverCount + "#n银元宝");
                }
                if (delGoldCount > 0) {
                    delMessage.append("#R" + delGoldCount + "#n金元宝");
                }

                String msg = MessageFormat.format("你花费了{0}，增加了#R{1}#n点紫气鸿蒙点数，当前剩余#R{2}#n点。", delMessage, 200 * num, nutMap.getInt("ziqi"));
                MessagePusher.pushMessage(session, new RespNotifyMiscEx(msg));

                roleService.updateRoleGoldAndSiver(role);
                ArrayList<FiedValue> list = new ArrayList<>();
                FiedValue fiedValue = new FiedValue();
                fiedValue.setType((short) 900);
                fiedValue.setVT((byte) 3);
                fiedValue.setValue((short) role.getPropsStatus().getInt("ziqi"));
                list.add(fiedValue);
                RespUpdate respUpdate = new RespUpdate();
                respUpdate.setRoleId(role.getRoleId());
                respUpdate.setList(list);
                MessagePusher.pushMessage(session, respUpdate);

                break;
            }
            case NotifyModules.NOTIFY_BUY_JIJI: {//购买急急如律令
                int num = Integer.parseInt(notify.getStatus());
                if (num <= 0) {
                    return;
                }
                if (num >10000){
                    return;
                }
                /*if (true){
                    MessagePusher.pushMessage(role,new RespNotifyMiscEx("购买急急如律令维护中"));
                    return;
                }*/
                int DBSiver = role.getSiver();
                if (DBSiver < 328 * num) {
                    int DBGold = role.getGold();
                    if (DBGold < 328 * num) {
                        MessagePusher.pushMessage(session, new RespMsg("你的元宝不足。"));
                        return;
                    } else {
                        SpringUtils.getRoleService().subtractGold(role, 328 * num, Reason.BUY_JIJI);
                        NutMap nutMap = role.getPropsStatus();
                        nutMap.setv("manguai", nutMap.getInt("manguai", 0) + 200 * num);
                        role.setPropsStatus(nutMap);
                        MessagePusher.pushMessage(session, new RespNotifyMiscEx("你花费了#R" + 328 * num + "#n金元宝，增加了#R" + 200 * num + "#n点急急如律令点数，当前剩余#R" + nutMap.getInt("manguai") + "#n点。"));
                    }
                } else {
                    roleService.subtractSiver(role, 328 * num, Reason.BUY_JIJI);
                    NutMap nutMap = role.getPropsStatus();
                    nutMap.setv("manguai", nutMap.getInt("manguai", 0) + 200 * num);
                    role.setPropsStatus(nutMap);
                    MessagePusher.pushMessage(session, new RespNotifyMiscEx("你花费了#R" + 328 * num + "#n银元宝，增加了#R" + 200 * num + "#n点急急如律令点数，当前剩余#R" + nutMap.getInt("manguai") + "#n点。"));
                }

                roleService.updateRoleGoldAndSiver(role);
                ArrayList<FiedValue> list = new ArrayList<>();
                FiedValue fiedValue = new FiedValue();
                fiedValue.setType((short) 312);
                fiedValue.setVT((byte) 3);
                fiedValue.setValue((short) role.getPropsStatus().getInt("manguai"));
                list.add(fiedValue);
                RespUpdate respUpdate = new RespUpdate();
                respUpdate.setRoleId(role.getRoleId());
                respUpdate.setList(list);
                MessagePusher.pushMessage(session, respUpdate);
                break;
            }
            case NotifyModules.NOTIFY_BUY_CHONGFENGSAN: {//购买紫气鸿蒙
                int num = Integer.parseInt(notify.getString());
                if (num <= 0) {
                    return;
                }
                /*if (true){
                    MessagePusher.pushMessage(role,new RespNotifyMiscEx("购买宠风散维护中"));
                    return;
                }*/
                int DBSiver = role.getSiver();
                if (DBSiver < 216 * num) {
                    int DBGold = role.getGold();
                    if (DBGold < 216 * num) {
                        MessagePusher.pushMessage(session, new RespMsg("你的元宝不足。"));
                        return;
                    } else {
                        SpringUtils.getRoleService().subtractGold(role, 216 * num, Reason.BUY_CHONGFENGSAN);
                        NutMap nutMap = role.getPropsStatus();
                        nutMap.setv("pet", nutMap.getInt("pet", 0) + 200 * num);
                        role.setPropsStatus(nutMap);
                        MessagePusher.pushMessage(session, new RespNotifyMiscEx("你花费了#R" + 216 * num + "#n金元宝，增加了#R" + 200 * num + "#n点宠风散点数，当前剩余#R" + nutMap.getInt("pet") + "#n点。"));
                    }
                } else {
                    roleService.subtractSiver(role, 216 * num, Reason.BUY_CHONGFENGSAN);
                    NutMap nutMap = role.getPropsStatus();
                    nutMap.setv("pet", nutMap.getInt("pet", 0) + 200 * num);
                    role.setPropsStatus(nutMap);
                    MessagePusher.pushMessage(session, new RespNotifyMiscEx("你花费了#R" + 216 * num + "#n银元宝，增加了#R" + 200 * num + "#n点宠风散点数，当前剩余#R" + nutMap.getInt("pet") + "#n点。"));
                }

                roleService.updateRoleGoldAndSiver(role);
                ArrayList<FiedValue> list = new ArrayList<>();
                FiedValue fiedValue = new FiedValue();
                fiedValue.setType((short) 3002);
                fiedValue.setVT((byte) 3);
                fiedValue.setValue((short) role.getPropsStatus().getInt("pet"));
                list.add(fiedValue);
                RespUpdate respUpdate = new RespUpdate();
                respUpdate.setRoleId(role.getRoleId());
                respUpdate.setList(list);
                MessagePusher.pushMessage(session, respUpdate);

                break;
            }
            case NotifyModules.NOTICE_OVER_INSTRUCTION: // 结束指引
                if (notify.getStatus().equals("25")) {//守护召唤指引结束
                    ReqGeneralNotify generalNotify = new ReqGeneralNotify();
                    generalNotify.setStatus("云霄童子");
                    generalNotify.setType((short) NotifyModules.CALL_GUARD);
                    generalNotify(session, generalNotify);
                }
                break;
            case NotifyModules.NOTIFY_TEAM_ASK_REFUSE: {//队伍投票拒绝
                Team team = SpringUtils.getBean(TeamService.class).getTeam(role.getRoleId());
                if (team != null) {
                    Role leaderRole = SpringUtils.getRoleService().getOnlinePlayer(team.getLeaderUid());
                    if (leaderRole != null) {
                        if (leaderRole.getConfirm().getConfirmType() == ConfirmType.TOWER_TEAM_FLY_UP) {
                            /**通天塔投票不同意*/
                            SpringUtils.getBean(TowerTaskHandler.class).flyUpBallotDisagree(role);
                        } else if (leaderRole.getConfirm().getConfirmType() == ConfirmType.ENTER_SHIDAO_MAP) {
                            /**进入试道场不同意*/
                            SpringUtils.getBean(ShiDaoHandler.class).ballotDisagree(role);
                        } else if (leaderRole.getConfirm().getConfirmType() == ConfirmType.CREATE_DUGEON) {
                            /**创建副本投票不同意*/
                            SpringUtils.getBean(DugeonTaskHandler.class).createBugeonBallotDisagree(role);
                        }
                    }
                }
                break;
            }
            case NotifyModules.NOTIFY_TEAM_ASK_AGREE: {//队伍投票同意
                Team team = SpringUtils.getBean(TeamService.class).getTeam(role.getRoleId());
                if (team != null) {
                    Role leaderRole = SpringUtils.getRoleService().getOnlinePlayer(team.getLeaderUid());
                    if (leaderRole != null) {
                        if (leaderRole.getConfirm().getConfirmType() == ConfirmType.TOWER_TEAM_FLY_UP) {
                            /**通天塔投票同意*/
                            SpringUtils.getBean(TowerTaskHandler.class).flyUpBallotAgree(role);
                        } else if (leaderRole.getConfirm().getConfirmType() == ConfirmType.ENTER_SHIDAO_MAP) {
                            /**进入试道场同意*/
                            SpringUtils.getBean(ShiDaoHandler.class).ballotAgree(role);
                        } else if (leaderRole.getConfirm().getConfirmType() == ConfirmType.CREATE_DUGEON) {
                            /**创建副本投票同意*/
                            SpringUtils.getBean(DugeonTaskHandler.class).createBugeonBallotAgree(role);
                        }
                    }
                }
                break;
            }
            case NotifyModules.NOTIFY_FINISH_GATHER:
                // TODO 暂时先这样加个判断处理，后续再看怎么优化
                /**产生一个采集结束事件*/
                EventDispatcher.getInstance().fireEvent(new GatherEndEvent(EventType.GATHER_END, role));
                break;
            case NotifyModules.NOTIFY_QUERY_SHIDAO_INFO:
                SpringUtils.getBean(ShiDaoHandler.class).sendRespShidaoScore(role);
                break;

            case NotifyModules.DELETE_STONE_ATTRIB:
                SpringUtils.getBean(PetStoneService.class).removeStone(role, Byte.parseByte(notify.getStatus()), notify.getString());
                break;
            case NotifyModules.NOTIFY_SUBMIT_PET:
                SpringUtils.getPetService().submitPet(role, Integer.parseInt(notify.getStatus()));
                break;
            case NotifyModules.NOTIFY_OPEN_LOGIN_GIFT:
                SpringUtils.getBean(ServenDayRewardHandler.class).open(role);
                break;
            case NotifyModules.NOTIFY_FETCH_LOGIN_GIFT:
                SpringUtils.getBean(ServenDayRewardHandler.class).fetchLoginGift(role, Byte.parseByte(notify.getStatus()));
                break;
            case NotifyModules.NOTIFY_COMBAT_GET_CUR_ROUND:
                Fight fight = SpringUtils.getFightService().getFightByRoleId(role.getRoleId());
                if(fight!=null){
                    MessagePusher.pushMessage(session, SpringUtils.getFightMessageService().round(fight.getRound(), 0));
                }
                break;
            case NotifyModules.NOTIFY_FETCH_SHOUCHONG_GIFT:
                SpringUtils.getBean(FirstPayRewardHandler.class).fetchReward(role);
                break;
            case NotifyModules.NOTIFY_LEVEL_UP_PARTY:
                SpringUtils.getBean(PartyService.class).upgrade(role);
                break;
            default:
                logger.error("未处理NOTIFY功能==CODE:{}", generalType);
                break;
        }
    }


    @RequestMapping
    public void reqApplyFriendItem(IoSession session, ReqApplyFriendItem reqApplyFriendItem) {
        //Todo 赠送百合提升友好度
        Role role = SessionUtils.getRoleBySession(session);
        //4|0|0
        String items = reqApplyFriendItem.getItems();
        String[] strings1 = items.split("\\|");

        if(strings1[0] != null){
            int nums = Integer.parseInt(strings1[0]);
            if(nums <=0){
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("物品数量必须大于0"));
                return;
            }
//            String recvName = reqApplyFriendItem.getName();

            Friend friend = role.getFriendBox().getFriendByGid(reqApplyFriendItem.getGid());
            friend.setFriendliness( friend.getFriendliness() + 88 * nums);

            SpringUtils.getEquipService().delRoloEquip("百合", nums, false, role);
            SpringUtils.getFriendService().loadFriends(role);

//            Role toRole = SpringUtils.getRoleService().getPlayerBy()
            Role friendRole = SpringUtils.getRoleService().getPlayerBy(Long.parseLong(friend.getGid()));
            Friend friend1 = friendRole.getFriendBox().getFriendByGid(role.getGid());
            friend1.setFriendliness( friend1.getFriendliness() + 88 * nums);
            SpringUtils.getFriendService().loadFriends(friendRole);
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("好友度增加成功"));
            SpringUtils.getNpcService().closeDlg(role, "SubmitFDIDlg");
        }

    }

    /**
     * 返回任务状态
     */
    @RequestMapping
    public void openSkillDlg(IoSession session, ReqRequestTaskStatus reqRequestTaskStatus) {
        //Todo 100级给个任务 判断状态
        RespTaskStatusInfo respTaskstatusinfo = new RespTaskStatusInfo();
        respTaskstatusinfo.setString(reqRequestTaskStatus.getString());
        Role role = SessionUtils.getRoleBySession(session);
        if (role.getLevel() >= 100) {
            respTaskstatusinfo.setStatus(true);
        } else {
            respTaskstatusinfo.setStatus(false);
        }
        MessagePusher.pushMessage(session, respTaskstatusinfo);
    }

    /**
     * 开关如意刷道令
     *
     * @param session
     * @param ReqRuyiStatus
     */
    @RequestMapping
    public void openRuyiStatus(IoSession session, ReqRuyiStatus ReqRuyiStatus) {
        Role role = SessionUtils.getRoleBySession(session);
        role.setPropsStatus(role.getPropsStatus().setv("ruyiStatus", ReqRuyiStatus.isStatus()));
        role.save();
        RespRuyiStatus respRuyiStatus = new RespRuyiStatus();
        respRuyiStatus.setStatus(ReqRuyiStatus.isStatus());
        MessagePusher.pushMessage(session, respRuyiStatus);
        if (ReqRuyiStatus.isStatus()) {
            MessagePusher.pushMessage(session, new RespMsg("你已开启如意刷道令功能。"));
        } else {
            MessagePusher.pushMessage(session, new RespMsg("你已关闭如意刷道令功能。"));
        }
    }


    /**
     * 角色列表
     * Todo 登录服务器第一步 必须验证!!!验证!!!
     *
     * @param session
     */
    @RequestMapping
    public void requestLogin(IoSession session, ReqLogin request) {
        String sid = request.getAccountId();
        sid = sid.substring(6);
        LoginAuth loginAuth = DataCache.LOGIN_AUTHS.get(sid);
//        if (loginAuth == null
////                || loginAuth.getAuthKey() != request.getAuth_key()
//                || loginAuth.getSeed() != request.getSeed()) {
//            RespOtherLogin respOtherLogin = new RespOtherLogin();
//            respOtherLogin.setContent("账号登录失败。#r(原因：9026)");
//            respOtherLogin.setResult((short) 0);
//            MessagePusher.pushMessage(session, respOtherLogin);
//            return;
//        }
        if (sid.contains("-")){
            ModuleCounterFilter.banIp(session);
            return;
        }
        if (sid.length() != "01l3bRUZ".length()){
            ModuleCounterFilter.banIp(session);
            return;
        }
        if (!SpringUtils.getRoleService().canLogin(sid,session)){
            return;
        }
        // 跨服登录
        if (SpringUtils.getBean(CrossServerConfig.class).isCenterServer()) {
            long playerId = loginAuth.getUid();
            Role role = SpringUtils.getRoleService().getPlayerBy(playerId);
            session.setAttribute(SessionProperties.ACCOUNT_SID, sid);
            List<RoleInfo> list = new ArrayList<>();
            RoleInfo roleInfo = new RoleInfo();
            roleInfo.setLast_login_time((int) role.getEnterTime());
            byte onlineStatus = Const.CHAR_LIST_T_NONE;
            roleInfo.setList(FieldUtils.roleInfo(role, onlineStatus));
            list.add(roleInfo);

            RespExistedRoleList respExistedRoleList = new RespExistedRoleList();
            respExistedRoleList.setOpenServerTime(new Long(System.currentTimeMillis() / 1000).intValue());
            respExistedRoleList.setList(list);
            respExistedRoleList.setAccount_online(Const.CHAR_LIST_T_NONE);//不在线
            MessagePusher.pushMessage(session, respExistedRoleList);
            return;
        }

        Account account = SpringUtils.getBean(AccountService.class).getAccount(sid);
        if (account != null) {
            session.setAttribute(SessionProperties.ACCOUNT_SID, sid);
            RespPushDebugInfo debugInfo = new RespPushDebugInfo();
            MessagePusher.pushMessage(session, debugInfo);



            // 如果是换线，直接进入游戏
//            NutMap nutMap = DataCache.account_uid.get(request.getAccountId().substring(6));
//            if (nutMap != null && SpringUtils.getBean(ServerService.class).getServer().getId() == 10000){
//                Role role = playerService.getPlayerBy(nutMap.getLong("kuafuUid"));
//                if (role == null){
//                    MessagePusher.pushMessage(session,new RespNotifyMiscEx("角色不存在"));
//                    return;
//                }
//                RoleService roleService = SpringUtils.getRoleService();
//                try {
//                    roleService.enterMap(session,role);
//                }catch (Exception e){
//                    logger.error("换线路失败=={}=={}",role.getRoleId(),role.getName(),e);
//                }
//            }else {
                ServerService serverService = SpringUtils.getBean(ServerService.class);
                Server server = serverService.getServer();
                playerService.listRoleInfos(sid, server.getName(), session);
//            }


//        RespReplyEcho replyEcho = new RespReplyEcho();
//        int peerTime = (int) (63000000 + System.currentTimeMillis() - AsktaoUtil.serverStartTime);
//        replyEcho.setPeerTime(peerTime);
//        MessagePusher.pushMessage(session, replyEcho);



//            RespShowReconnectPara respShowReconnectPara = new RespShowReconnectPara();
//            respShowReconnectPara.setDist_name(server.getName());
//            respShowReconnectPara.setEnd_time(new Long(new Date().getTime() / 1000).intValue());
//            respShowReconnectPara.setMsg(server.getSonIp() + "," + server.getPort() + "," + request.getAuth_key() + "," + request.getSeed());
//            MessagePusher.pushMessage(session, respShowReconnectPara);
//            logger.error("登录游戏=={}=={}",Json.toJson(request));

        } else {
            RespOtherLogin respOtherLogin = new RespOtherLogin();
            respOtherLogin.setContent("账号登录失败。#r(原因：9027)");
            respOtherLogin.setResult((short) 0);
            MessagePusher.pushMessage(session, respOtherLogin);
            ModuleCounterFilter.banIp(session);
        }
    }

    /**
     * 接受心跳包
     *
     * @param session
     * @param reqEcho
     */
    @RequestMapping
    public void heart(IoSession session, ReqEcho reqEcho) {
        /**产生一个心跳事件*/
        Role role = SessionUtils.getRoleBySession(session);
        if (role != null) {//登录的时候会报空
//            /**更新收到心跳时间*/
            long prevHeartTime = role.getPrevHeartTime();
            role.setPrevHeartTime(System.currentTimeMillis());
//
//            checkHeart(role, prevHeartTime,session);
            EventDispatcher.getInstance().fireEvent(new HeartBeatEvent(EventType.HEART_BEAT, role, prevHeartTime));
        }
        {
            Object object = session.getAttribute("xingtiaoxingtiaoxingtiaoxingtiao");
            if (object == null) {
                object = new ArrayList<Long>();
                session.setAttribute("xingtiaoxingtiaoxingtiaoxingtiao",object);
            }
            ArrayList<Long> arrayList = (ArrayList<Long>) object;
            try {
                arrayList.add(System.currentTimeMillis());
//                logger.error("==={}",Json.toJson(arrayList));
                if (arrayList.size() >= 10){
                    session.setAttribute("xingtiaoxingtiaoxingtiaoxingtiao",new ArrayList<Long>());
                    if (arrayList.get(1) - arrayList.get(0) <= 8000
                            && arrayList.get(2) - arrayList.get(1) <= 8000
                            && arrayList.get(3) - arrayList.get(2) <= 8000
                            && arrayList.get(4) - arrayList.get(3) <= 8000
                            && arrayList.get(5) - arrayList.get(4) <= 8000
                            && arrayList.get(6) - arrayList.get(5) <= 8000
                            && arrayList.get(7) - arrayList.get(6) <= 8000
                            && arrayList.get(8) - arrayList.get(7) <= 8000
                            && arrayList.get(9) - arrayList.get(8) <= 8000){
                        logger.error("心跳检测到加速器=={}",role.getName());
                        MessagePusher.pushMessage(session, new RespNotifyMiscEx("#R服务器认为你开了加速软件,再次检测到将会封停账号!!!"));
                        MessagePusher.pushMessage(session, new RespNotifyMiscEx("#R服务器认为你开了加速软件,再次检测到将会封停账号!!!"));
                        MessagePusher.pushMessage(session, new RespNotifyMiscEx("#R服务器认为你开了加速软件,再次检测到将会封停账号!!!"));
                        MessagePusher.pushMessage(session, new RespNotifyMiscEx("#R服务器认为你开了加速软件,再次检测到将会封停账号!!!"));
                        MessagePusher.pushMessage(session, new RespNotifyMiscEx("#R服务器认为你开了加速软件,再次检测到将会封停账号!!!"));
//                        SpringUtils.getBean(PkService.class).add2Prison(role);
                        ScheduledFuture<?> timeOutTask = SchedulerManager.getInstance().schedule(new Runnable() {
                            @Override
                            public void run() {
                                logger.error("加速器断开连接=={}",role.getName());
                                session.closeNow();
                            }
                        }, 3000);
                        return;
                    }
                }
            }catch (Exception e){
                logger.error("心跳包出错==={}==={}",Json.toJson(arrayList),e);
                logger.error("心跳包出错==角色名称={}==roleId={}",role.getName(),role.getRoleId());
            }
        }
        Object lastHeart = session.getAttribute(Const.heartTime);
        int peerTime;
        ReqEcho oldReqEcho;
        if (lastHeart != null) {
            oldReqEcho = (ReqEcho) lastHeart;
            peerTime = oldReqEcho.getPeerTime() + (reqEcho.getCurrentTime() - oldReqEcho.getCurrentTime());
            reqEcho.setPeerTime(peerTime);
        } else {
            peerTime = (int) (63000000 + System.currentTimeMillis() - AsktaoUtil.serverStartTime);
            reqEcho.setPeerTime(peerTime);
        }
        session.setAttribute(Const.heartTime, reqEcho);
        RespReplyEcho RespReplyEcho = new RespReplyEcho();
        RespReplyEcho.setPeerTime(peerTime);
        MessagePusher.pushMessage(session, RespReplyEcho);


    }

    /**检测心跳包数量*/
    private void checkHeart(Role role, long prevHeartTime,IoSession session) {
        if (role == null) {return ;}

        int currentMin = (int) (System.currentTimeMillis() / TimeUtil.ONE_MINUTE);
        /**增加每分钟心跳包的数量*/
        int count = role.getHeartCounts().getOrDefault(currentMin, 0) + 1;
        role.getHeartCounts().put(currentMin, count);

        /**检测是否有非法加速情况*/
        if (isHeartUnlaw(role, currentMin, prevHeartTime)) {
            /**判断有加速情况*/

            logger.warn("{}({})使用加速器！！，包的数量:{}, 上一心跳时间:{}", role.getUid(), role.getName(), JsonUtils.object2String(role.getHeartCounts()), prevHeartTime);
            RespOtherLogin respOtherLogin = new RespOtherLogin();
            respOtherLogin.setContent("检测到使用第三方辅助软件，请正常游戏");
            respOtherLogin.setResult((short) 2);
            MessagePusher.pushMessage(role, respOtherLogin);

            role.getHeartCounts().clear();
            session.closeNow();
        }
    }

    /**是否有心跳非法情况*/
    private boolean isHeartUnlaw(Role role, int currentMin, long prevHeartTime) {
        int count = role.getHeartCounts().getOrDefault(currentMin, 0);
        if (count >= Const.HEART_COUNT_SINGLE_UNLAW) {
            return true;
        }

        if (role.getHeartCounts().size() > Const.HEART_CHECK_MINUTE_COUNT) {
            int speedCount = (int) role.getHeartCounts().values().stream().filter(v -> v >= Const.HEART_COUNT_PER_MINUTE_UNLAW).count();

            /**清除之前的记录*/
            role.getHeartCounts().remove(currentMin-Const.HEART_CHECK_MINUTE_COUNT);

            if (speedCount >= Const.HEART_CHECK_MINUTE_COUNT) {
                return true;
            }
        }

        /**时间间隔太长也有问题*/
        if (prevHeartTime > 0 && System.currentTimeMillis() - prevHeartTime >= 30 * TimeUtil.ONE_SECOND) {
            return true;
        }

        return false;
    }
    // 过滤的字符
    public static String filterStr = "[- _`~!@#$%^&*()--+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t▓";
    /**
     * 创建角色
     *
     * @param session
     */
    @RequestMapping
    public void createRole(IoSession session, ReqCreateNewChar reqCreateNewChar) {
        ServerService serverService = SpringUtils.getBean(ServerService.class);
        String char_name = reqCreateNewChar.getChar_name();
        if (char_name.contains("�")) {
            MessagePusher.pushMessage(session,new RespNotifyMiscEx("昵称只允许数字、中文、字母。。"));
            return;
        }
        Pattern p = Pattern.compile(filterStr);
        Matcher m = p.matcher(char_name);
        if (m.find()) {
            MessagePusher.pushMessage(session,new RespNotifyMiscEx("昵称只允许数字、中文、字母。"));
            return;
        }

        String sid = SessionManager.INSTANCE.getSessionAttr(session, SessionProperties.ACCOUNT_SID, String.class);
        if (Strings.isEmpty(sid)) {
            RespOtherLogin respOtherLogin = new RespOtherLogin();
            respOtherLogin.setContent("请重新登录账号。#r（原因：9028）");
            respOtherLogin.setResult((short) 0);
            MessagePusher.pushMessage(session, respOtherLogin);
            return;
        }
        RoleService roleService = SpringUtils.getBean(RoleService.class);
        Server server = serverService.getServer();
        PlayerService playerService = SpringUtils.getBean(PlayerService.class);
        AccountService accountService = SpringUtils.getAccountService();
        Account account =accountService.getAccount(sid);
        if (serverService.getServer().getId() == 10000 && account.getPrivilege() <200){
            MessagePusher.pushMessage(session,new RespNotifyMiscEx("跨服专线不能创建角色。"));
            return;
        }
        List<RoleInfo> roleInfos = playerService.listRoleInfos(sid, server.getName(), null);

        if (roleInfos.size() >= 1) {
            RespMsg respMsg = new RespMsg();
            respMsg.setMsg("为了更好的游戏体验#r#R本服限制注册1个角色，您已经有1个角色了！");
            MessagePusher.pushMessage(session, respMsg);
            return;
        }
        Role newRole = roleService.createRole(session, sid, reqCreateNewChar);
        if (newRole == null) {
            return;
        }

        /** 产生一个创建角色的事件 */
        EventDispatcher.getInstance().fireEvent(new CreateRoleEvent(EventType.CREATE_ROLE, newRole));

        SpringUtils.getBean(MainTaskHandler.class).acceptFirstMainTask(newRole);

        /**创建角色成功需要移除匿名 不然会断线*/
        SessionManager.INSTANCE.removeFromAnonymous(session);

        playerService.listRoleInfos(sid, server.getName(), session);
        //创建角色成功
        RespCreateNewRole respCreateNewRole = new RespCreateNewRole();
        respCreateNewRole.setName(newRole.getName());
        respCreateNewRole.setGid(newRole.getGid());
        MessagePusher.pushMessage(session, respCreateNewRole);
    }

    /**
     * 随机取名
     *
     * @param session
     * @param reqRandomName
     */
    @RequestMapping
    public void randomName(IoSession session, ReqRandomName reqRandomName) {
        RespRandomName respRandomName = new RespRandomName();
        respRandomName.setName(RandomName.getChineseName());
        MessagePusher.pushMessage(session, respRandomName);
    }

    /**
     * 切换称谓
     *
     * @param session
     * @param ChangeTitle
     */
    @RequestMapping
    public void changeTitle(IoSession session, ReqChangeTitle ChangeTitle) {
        Role role = SessionUtils.getRoleBySession(session);
        RoleService roleService = SpringUtils.getBean(RoleService.class);
        roleService.changeTitle(role, ChangeTitle.getSelect());
    }

    /**
     * 切换称谓
     *
     * @param session
     * @param reqChangeSect
     */
    @RequestMapping
    public void reqChangeSect(IoSession session, ReqChangeSect reqChangeSect) {
        Role role = SessionUtils.getRoleBySession(session);
        SpringUtils.getMapService().changeMap(role, 5000, 105, 69);
    }
}
